package org.uk.splitsbrowser.server;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.uk.splitsbrowser.client.presenter.UserService;
import org.uk.splitsbrowser.shared.SplitsbrowserException;
import org.uk.splitsbrowser.shared.User;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.orientechnologies.orient.object.db.OObjectDatabaseTx;

public class UserServiceImpl extends RemoteServiceServlet implements UserService {

	private static final long serialVersionUID = 5157455058508070690L;

	private final long DURATION = 1000 * 60 * 60 * 24 * 14; // duration
															// remembering
															// login. 2 weeks

	private static RandomString passwordGen = new RandomString(6);

	private void checkLogin(String key) throws SplitsbrowserException {
		if (key != "") {
			User user = getUser(key);
			if (user != null) {

			}
		}

	}

	@Override
	public void saveUser(User user) throws SplitsbrowserException {
		checkLogin(user.getId());

	}

	@Override
	public void newUser(User user) throws SplitsbrowserException {
		// No login is required when creating a new user

		// We save the user and
		user.setPassword(passwordGen.nextString());

	}

	@Override
	public void deleteUser(String id) throws SplitsbrowserException {
		checkLogin(id);

	}

	@Override
	public User[] queryUser(String queryString, int offset, int count) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public User getUser(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String logon(User user, String password) throws SplitsbrowserException {

		// We should move to storing encrypted passwords
		// String hashFromDB = /*(obtain hash from user's db entry)*/;
		// boolean valid = BCrypt.checkpw(password, hashFromDB);

		if (user.getPassword() == password) {
			HttpServletRequest request = this.getThreadLocalRequest();
			HttpSession session = request.getSession();

			// String sessionID = /*(Get sessionID from server's response to
			// your login request.)*/;
			Date expires = new Date(System.currentTimeMillis() + DURATION);
			// TODO
			// Cookies.setCookie("sid", sessionID, expires, null, "/", false);

			session.setAttribute("authenticatedUserName", user.getEmail());

			return (session.getId());
		} else {
			return (null);
		}
	}

	@Override
	public void logoff() {
		HttpServletRequest request = this.getThreadLocalRequest();
		HttpSession session = request.getSession();

		session.setAttribute("authenticatedUserName", null);

	}

	public User UserForSession(String sessionId) {
		return null;
	}

	@Override
	public User queryUser(String userEmail) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void requestPasswordReset(String userEmail) throws SplitsbrowserException {
		// Find the user. If the email exists then reset the password mail it to
		// them
		User user = queryUser(userEmail);
		if (user != null) {
			OObjectDatabaseTx db = DBService.getDB();
			try {
				String password = passwordGen.nextString();
				user.setPassword(password);
				db.save(user);
				// send mail to user
				sendPasswordEmail(userEmail, password);
			} finally {
				db.close();
			}
		} else {
			throw new SplitsbrowserException("Email not found");
		}
	}

	private void sendPasswordEmail(String email, String password) throws SplitsbrowserException {
		// Send an email to notify use of password

		// Sender's email ID needs to be mentioned
		String from = "support@splitsbrowser.org.uk";

		String host = "localhost";

		// Set relivant system properties
		Properties properties = System.getProperties();

		properties.setProperty("mail.smtp.host", host);

		// Get the default Session object.
		Session mailSession = Session.getDefaultInstance(properties);

		try {
			// Create a default MimeMessage object.
			MimeMessage message = new MimeMessage(mailSession);
			message.setFrom(new InternetAddress(from));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));

			message.setSubject("Splitsbrowser ");
			message.setText("Welcome to Splitsbrowser");

			// Send message
			Transport.send(message);

			// System.out.println("Sent message successfully....");
		} catch (MessagingException mex) {
			mex.printStackTrace();
			throw new SplitsbrowserException(
					"Unexpected error - Could not send confirmation email when setting user password");

		}

	}

}
